# -*- coding: utf-8 -*-
from google.appengine.ext import webapp                                        
from google.appengine.ext.webapp.util import run_wsgi_app                      
import logging                                                                 
     
from StringIO import StringIO                                                  
import traceback
import xmlrpclib
from xmlrpcserver import XmlRpcServer
from google.appengine.ext import db
import datetime
from xmw import tianya
import xmw
from xmw import error
from google.appengine.api import mail
from xmw.db.mail import *
class Mail_Mgr:
    def send_mail(self,recept,subject,content):

        message = mail.EmailMessage(sender=u"""西门外<ximenwai.liu@gmail.com>""",
                            subject=subject)

        message.to = recept
        message.body = xmw.xmw_zip_decoding(content)

        message.send()
    
    def send_mail_multi(self,recepts,subject,content):
        if recepts is None:
            return
        if len(recepts) == 0:
            return
        
        task    =MailTask()
        subject=xmw.xmw_decoding(subject).decode('utf-8')
        task.subject =subject
        
        content =xmw.xmw_zip_decoding(content)
        content=content.decode('utf-8')
        task.content =content
        task.lst_recepts = recepts
        mail_counter = MailTaskCounter()
        cnt= mail_counter.inc_and_get()
        task.seq = cnt
        task.save()
        return
    
        
    def send_mail_multi_bak(self,recepts,subject,content):
        message = mail.EmailMessage(sender=u"""西门外<ximenwai.liu@gmail.com>""")
        message.subject = xmw.xmw_decoding(subject)

        
        #message.body = xmw.xmw_zip_decoding(content)
        message.html=xmw.xmw_zip_decoding(content)
        logging.info("ready to send mail:\n recepts:%s\n subject:%s \n %s"%(str(recepts),
                                                                             message.subject,
                                                                             message.html))
        for recept in recepts:
            message.to=recept
            message.send()
        message.to='ximenwai.liu@gmail.com'
        message.send()
        #message.
        

        return 
        
    def echo(self,msg):
        return msg
            
            
class XMLRpcHandler(webapp.RequestHandler):                                    
    rpcserver = None
                                
    def __init__(self):         
        self.rpcserver = XmlRpcServer()                                        
        mail_mgr = Mail_Mgr()                                                    
        self.rpcserver.register_class('mail_mgr',xmw.XmlRpcWrapper(mail_mgr))                               
                                                                               
    def post(self):
        request = StringIO(self.request.body)
        request.seek(0)                                                        
        response = StringIO()                                                  
        try:
            self.rpcserver.execute(request, response, None)                    
        except Exception, e:                                                   
            logging.error('Error executing: '+str(e))                          
            for line in traceback.format_exc().split('\n'):                    
                logging.error(line)
        finally:
            response.seek(0)  
                                                                               
        rstr = response.read()                                                 
        self.response.headers['Content-type'] = 'text/xml'                     
        self.response.headers['Content-length'] = "%d"%len(rstr)               
        self.response.out.write(rstr)
                                                                               
application = webapp.WSGIApplication(                                          
                                     [('/xmlrpc/xmw_mail', XMLRpcHandler)],
                                     debug=True)                               
def main():
  run_wsgi_app(application)                                                    
        
if __name__ == "__main__":
    main()